<template>
  <div class="p-2">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[10px]">
        <Card>
          <Form ref="queryFormRef" :model="queryParams" layout="inline">
            <FormItem label="年份" name="year">
              <Select v-model:value="queryParams.year" placeholder="请选择年份" allow-clear style="width: 120px">
                <SelectOption value="2025">2025</SelectOption>
                <SelectOption value="2024">2024</SelectOption>
                <SelectOption value="2023">2023</SelectOption>
                <SelectOption value="2022">2022</SelectOption>
              </Select>
            </FormItem>
            <FormItem label="月份" name="month">
              <Select v-model:value="queryParams.month" placeholder="请选择月份" allow-clear style="width: 120px">
                <SelectOption value="01">1月</SelectOption>
                <SelectOption value="02">2月</SelectOption>
                <SelectOption value="03">3月</SelectOption>
                <SelectOption value="04">4月</SelectOption>
                <SelectOption value="05">5月</SelectOption>
                <SelectOption value="06">6月</SelectOption>
                <SelectOption value="07">7月</SelectOption>
                <SelectOption value="08">8月</SelectOption>
                <SelectOption value="09">9月</SelectOption>
                <SelectOption value="10">10月</SelectOption>
                <SelectOption value="11">11月</SelectOption>
                <SelectOption value="12">12月</SelectOption>
              </Select>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="handleQuery">预测</Button>
              <Button @click="resetQuery" style="margin-left: 8px">重置</Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    </transition>

    <Card>
      <template #title>
        <Row :gutter="10" class="mb8" style="margin-bottom: 0">
          <Col :span="1.5">
            <Button type="default" @click="handleExport" v-access:code="['data:table:export']">导出</Button>
          </Col>
          <Col :span="1.5" style="margin-left: auto">
            <Button @click="showSearch = !showSearch">{{ showSearch ? '收起' : '展开' }}</Button>
          </Col>
        </Row>
      </template>

      <Table
        :loading="loading"
        :dataSource="tableList"
        :columns="columns"
        :pagination="false"
        :row-key="(record, index) => index"
        :scroll="{ x: 'max-content' }"
      />

      <Pagination
        v-show="total > 0"
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        show-size-changer
        show-total
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        style="margin-top: 16px; text-align: right"
      />
    </Card>

    <!-- 添加或修改数据对话框
    <Modal
      :title="dialog.title"
      v-model:open="dialog.visible"
      width="500px"
      :confirm-loading="buttonLoading"
      @ok="submitForm"
      @cancel="cancel"
    >
      <Form ref="tableFormRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <FormItem label="编号" name="dataCode">
          <Input v-model:value="form.dataCode" placeholder="请输入编号" />
        </FormItem>
        <FormItem label="表名" name="dataTable">
          <Input v-model:value="form.dataTable" placeholder="请输入表名" />
        </FormItem>
        <FormItem label="表中文名" name="dataTableName">
          <Input v-model:value="form.dataTableName" placeholder="请输入表中文名" />
        </FormItem>
        <FormItem label="SQL语句" name="dataSql">
          <Input.TextArea v-model:value="form.dataSql" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="规则公式" name="dataFormula">
          <Input.TextArea v-model:value="form.dataFormula" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="备注" name="remark">
          <Input.TextArea v-model:value="form.remark" placeholder="请输入内容" :rows="4" />
        </FormItem>
      </Form>
    </Modal> -->
  </div>
</template>

<script setup name="Table" lang="ts">
import { getCurrentInstance, ref, reactive, toRefs, onMounted, nextTick } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import {
  Card,
  Form,
  FormItem,
  Input,
  Button,
  Table,
  Pagination,
  Modal,
  Row,
  Col,
  Space,
  Tooltip,
  Popconfirm,
  Select,
  SelectOption,
  message,
} from 'ant-design-vue';
// 图标组件 - 使用 Ant Design Vue 内置图标或移除图标
import { listTable } from '#/api/operate/monthPurchasePlan/show';
import type { TableVO, TableQuery, TableForm } from '#/api/operate/monthPurchasePlan/showTypes';
import { downloadExcel } from '#/utils/file/download';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const tableList = ref<TableVO[]>([]);
const allDataList = ref<TableVO[]>([]); // 存储所有数据用于客户端分页
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);

const queryFormRef = ref();
const tableFormRef = ref();

const dialog = reactive<{ visible: boolean; title: string }>({
  visible: false,
  title: ''
});

const columns = [
  {
    title: '地市级公司代码',
    dataIndex: 'ba_city_org_code',
    key: 'ba_city_org_code',
    align: 'center',
  },
  {
    title: '地市级公司简称',
    dataIndex: 'ba_city_org_short_name',
    key: 'ba_city_org_short_name',
    align: 'center',
  },
  {
    title: '商品代码',
    dataIndex: 'md05_product_code',
    key: 'md05_product_code',
    align: 'center',
  },
  {
    title: '商品名称',
    dataIndex: 'md05_product_name',
    key: 'md05_product_name',
    align: 'center',
  },
  {
    title: '商品期初库存量',
    dataIndex: 'md02_product_init_stk_qty',
    key: 'md02_product_init_stk_qty',
    align: 'center',
  },
  {
    title: '商品期初库存额',
    dataIndex: 'md02_product_init_stk_amt',
    key: 'md02_product_init_stk_amt',
    align: 'center',
  },
  {
    title: '商品购进量',
    dataIndex: 'md02_product_buy_qty',
    key: 'md02_product_buy_qty',
    align: 'center',
  },
  {
    title: '商品销售量',
    dataIndex: 'md02_product_sale_qty',
    key: 'md02_product_sale_qty',
    align: 'center',
  },
  {
    title: '商品调拨调出数量',
    dataIndex: 'md02_product_allot_allotout_carton_qty',
    key: 'md02_product_allot_allotout_carton_qty',
    align: 'center',
  },
  {
    title: '报损数量',
    dataIndex: 'md04_loss_qty',
    key: 'md04_loss_qty',
    align: 'center',
  }
];

const initFormData: TableForm = {
  ba_city_org_code: undefined,
  ba_city_org_short_name: undefined,
  md05_product_code: undefined,
  md05_product_name: undefined,
  md02_product_init_stk_qty: undefined,
  md02_product_init_stk_amt: undefined,
  md02_product_buy_qty: undefined,
  md02_product_sale_qty: undefined,
  md02_product_allot_allotout_carton_qty: undefined,
  md04_loss_qty: undefined
};

const data = reactive<{
  form: TableForm;
  queryParams: TableQuery & { pageNum: number; pageSize: number };
  rules: Record<string, any[]>;
}>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dataCode: undefined,
    userId: undefined,
    param: {},
    year: '2024',
    month: '10',
    week: undefined
  },
  rules: {
    dataCode: [
      { required: true, message: "编号不能为空", trigger: "blur" }
    ],
    dataTable: [
      { required: true, message: "表名不能为空", trigger: "blur" }
    ],
    dataTableName: [
      { required: true, message: "表中文名不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 更新表格显示数据(客户端分页) */
const updateTableList = () => {
  const startIndex = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const endIndex = startIndex + queryParams.value.pageSize;
  tableList.value = allDataList.value.slice(startIndex, endIndex);
};

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listTable(queryParams.value);
    console.log('API 返回数据:', res);
    
    // 根据后端实际返回的数据结构处理
    let dataList: TableVO[] = [];
    if (Array.isArray(res)) {
      // 如果直接返回数组
      dataList = res;
    } else if (res && Array.isArray(res.data)) {
      // 如果返回的是 { data: [...] } 结构
      dataList = res.data;
    } else if (res && Array.isArray(res.rows)) {
      // 如果返回的是 { rows: [...], total: number } 结构
      dataList = res.rows;
    } else {
      console.warn('未知的数据结构:', res);
      dataList = [];
    }
    
    // 保存全量数据用于分页
    allDataList.value = dataList;
    total.value = dataList.length;
    
    // 客户端分页
    updateTableList();
    
    console.log('处理后的表格数据:', tableList.value);
    console.log('数据总数:', total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
    tableList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  tableFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加数据";
};


/** 导出按钮操作 */
const handleExport = async () => {
  // 构建筛选条件提示
  const conditions: string[] = [];
  if (queryParams.value.year) conditions.push(`年份:${queryParams.value.year}`);
  if (queryParams.value.month) conditions.push(`月份:${queryParams.value.month}月`);
  
  const conditionText = conditions.length > 0 ? `(筛选条件: ${conditions.join(', ')})` : '(全部数据)';
  const hideLoading = message.loading(`正在导出数据${conditionText}...`, 0);
  
  try {
    // 获取当前筛选后的数据
    const res = await listTable(queryParams.value);
    
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }
    
    // 检查是否有数据
    if (dataList.length === 0) {
      message.warning('当前筛选条件下没有数据可导出');
      return;
    }
    
    // 转换为CSV格式
    const headers = ['地市级公司代码', '地市级公司简称', '商品代码', '商品名称', '商品期初库存量', '商品期初库存额', '商品购进量', '商品销售量', '商品调拨调出数量', '报损数量'];
    const csvContent = [
      headers.join(','),
      ...dataList.map((item: any) => [
        item.ba_city_org_code || '',
        item.ba_city_org_short_name || '',
        item.md05_product_code || '',
        item.md05_product_name || '',
        item.md02_product_init_stk_qty || '',
        item.md02_product_init_stk_amt || '',
        item.md02_product_buy_qty || '',
        item.md02_product_sale_qty || '',
        item.md02_product_allot_allotout_carton_qty || '',
        item.md04_loss_qty || ''
      ].join(','))
    ].join('\n');
    
    // 添加BOM头以支持中文
    const BOM = '\uFEFF';
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
    
    // 构建文件名
    let fileName = '月维度采购计划';
    if (queryParams.value.year) fileName += `_${queryParams.value.year}年`;
    if (queryParams.value.month) fileName += `${queryParams.value.month}月`;
    fileName += `_${new Date().getTime()}.csv`;
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', fileName);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    message.success(`导出成功! 共导出 ${dataList.length} 条数据`);
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败');
  } finally {
    hideLoading();
  }
};

/** 分页变化 */
const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page;
  updateTableList(); // 使用客户端分页,无需重新请求
};

/** 分页大小变化 */
const handlePageSizeChange = (_current: number, size: number) => {
  queryParams.value.pageSize = size;
  queryParams.value.pageNum = 1;
  updateTableList(); // 使用客户端分页,无需重新请求
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
